package com.jsnkj.basic.activity

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.view.View
import androidx.core.content.FileProvider
import com.jsnkj.basic.R
import com.jsnkj.basic.bean.HomeItemBean
import com.jsnkj.basic.config.SpConfig
import com.jsnkj.basic.databinding.ActivityDownBinding
import com.jsnkj.basic.mvvm.BaseKtActivity
import com.jsnkj.basic.mvvm.HttpViewModel
import com.jsnkj.basic.util.jsonToClass
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.jsnkj.basic.LibraryConfig
import com.yang.http.down.DownloadInfo
import com.yang.http.down.DownloadManager
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.io.File


class DownActivity : BaseKtActivity<ActivityDownBinding, HttpViewModel>(), View.OnClickListener {
    override val layoutId: Int
        get() = R.layout.activity_down

    companion object {
        fun startDownActivity(activity: Activity, beanJson: String, goSplash: Boolean = false) {
            val intent = Intent(activity, DownActivity::class.java)
            intent.putExtra("home_item_bean", beanJson)
            intent.putExtra("is_go_to_splash", goSplash)
            activity.startActivity(intent)
        }
    }

    var isGotoSplash: Boolean = false
    var bean: HomeItemBean? = null
    private var downloadInfo: DownloadInfo? = null

    override fun initView(savedInstanceState: Bundle?) {
        mVDB.clickListener = this

        EventBus.getDefault().register(this)
        mVDB.progressDown.height = com.jsnkj.basic.widget.colorfulprogressbar.DisplayDownUtil.dip2px(this, 20F)
        mVDB.progressDown.setStyle(com.jsnkj.basic.widget.colorfulprogressbar.ColorfulProgressbar.STYLE_NORMAL)
        mVDB.progressDown.setProgressColorRes(R.color.color_ea582a)
        mVDB.progressDown.maxProgress = 100

        isGotoSplash = intent.getBooleanExtra("is_go_to_splash", false)

        var beanJson = intent.getStringExtra("home_item_bean") ?: ""
        if (beanJson.isEmpty()) {
            com.jsnkj.basic.util.ToastUtils.show("下载地址为空")
            onBackPressed()
            return
        }
        bean = beanJson.jsonToClass<HomeItemBean>()
        if (null == bean || bean!!.down_url.isNullOrEmpty()) {
            com.jsnkj.basic.util.ToastUtils.show("下载地址为空")
            onBackPressed()
            return
        }
        bean?.let { bean ->

            val options: RequestOptions = RequestOptions()
                .placeholder(R.mipmap.logo) //图片加载出来前，显示的图片
                .fallback(R.mipmap.logo) //url为空的时候,显示的图片
                .error(R.mipmap.logo) //图片加载失败后，显示的图片


            Glide.with(this).load(bean.icon).apply(options).into(mVDB.imgLogo)

            bean.title?.let {
                mVDB.tvTitle.text = it
            }

            bean.remark?.let {
                mVDB.tvRemark.text = it
            }

            DownloadManager.getInstance().download(bean.down_url, SpConfig.DOWN_APK_PATH)
        }

    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun update(info: DownloadInfo) {
        if (DownloadInfo.DOWNLOAD == info.downloadStatus) {
            downloadInfo = info

            if (info.getTotal() === 0L) {
                mVDB.progressDown.progress = 0
            } else {
                val progress = info.progress * 100 / info.total
                mVDB.progressDown.progress = progress
//                LogUtils.e("下载进度：  progress == ${progress}")
            }

        } else if (DownloadInfo.DOWNLOAD_OVER == info.downloadStatus) {
            mVDB.progressDown.progress = 100
            installApk(info.savePath)
        } else if (DownloadInfo.DOWNLOAD_PAUSE == info.downloadStatus) {
            com.jsnkj.basic.util.LogUtils.e("下载暂停")
        } else if (DownloadInfo.DOWNLOAD_CANCEL == info.downloadStatus) {
            mVDB.progressDown.progress = 0
            com.jsnkj.basic.util.LogUtils.e("下载取消")
        } else if (DownloadInfo.DOWNLOAD_ERROR == info.downloadStatus) {
            com.jsnkj.basic.util.LogUtils.e("下载出错：   ")
            com.jsnkj.basic.util.ToastUtils.show("下载失败")
        }
    }


    fun installApk(filePath: String) {
        com.jsnkj.basic.util.LogUtils.e("安装路径： path == $filePath")
        val intent = Intent(Intent.ACTION_VIEW)
        //注意这里的app-release.apk为你要安装在模拟器上的apk名字
        val file = File(filePath)
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
        //判读版本是否在7.0以上
        if (Build.VERSION.SDK_INT >= 24) {
            val apkUri =
                FileProvider.getUriForFile(this, LibraryConfig.APPLICATION_ID + ".fileprovider", file)
            //添加这句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive")
        } else {
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive")
        }
        startActivity(intent)
        this.finish()
    }


    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    override fun onClick(view: View) {
        when (view.id) {
            R.id.tv_cancel_download, R.id.image_return -> {
                if (null != downloadInfo) {
                    DownloadManager.getInstance().cancelDownload(downloadInfo)
                }
                onBackPressed()
            }

            R.id.img_logo -> {
//                installToAPk(savePath)
            }
        }
    }


}